package com.ice.framework.web.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.AutoConfigureAfter;
import org.springframework.boot.autoconfigure.http.HttpMessageConverters;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import java.util.List;

/**
 * @author wangwei
 * @Date 2021/12/31 17:17
 */
@Configuration
@AutoConfigureAfter(value = HttpMessageConvertersConfig.class)
public class CustomerWebMvcConfigurer implements WebMvcConfigurer {

    @Value("${web.cor.path:/api/**}")
    private String corPath;

    @Autowired
    private HttpMessageConverters httpMessageConverters;

    /**
     * 清除掉默认的转换器，使用自定义的转换器
     */
    @Override
    public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
        converters.clear();
        converters.addAll(this.httpMessageConverters.getConverters());
    }

    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping(corPath).allowedOrigins("*").allowedHeaders("*").allowedMethods("*");
    }

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("doc.html").addResourceLocations("classpath:/META-INF/resources/");
        registry.addResourceHandler("/webjars/**").addResourceLocations("classpath:/META-INF/resources/webjars/");
    }

}
